import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class LinkSpanData {
  LinkSpanData({
    required this.text,
    required this.onTap,
    this.style,
  });

  final String text;
  final TextStyle? style;
  final VoidCallback onTap;
}

/// 文本中存在可点击的文字
///
/// CustomLinkTextSpanWidget(
///   text: '发布到社区须遵循《社区公约》，请仔细阅读，之后可随时更改为自己可见。',
///   style: const TextStyle(color: Colors.black),
///   links: [
///     LinkSpanData(
///       text: '《社区公约》',
///       onTap: () {
///         print('点击了社区公约');
///       },
///       style: const TextStyle(color: Colors.blue),
///     ),
///   ],
/// )
///
class CustomLinkTextSpanWidget extends StatelessWidget {
  CustomLinkTextSpanWidget({
    required this.text,
    required this.links,
    Key? key,
    this.style,
  })  : assert(text.trim().isNotEmpty && links.isNotEmpty),
        super(key: key);

  final String text;
  final List<LinkSpanData> links;
  final TextStyle? style;

  @override
  Widget build(BuildContext context) {
    var end = 0;
    final spans = <TextSpan>[];
    final length = links.length;

    for (var i = 0; i < length; i++) {
      final link = links[i];
      final index = text.indexOf(link.text, end);
      if (index != -1) {
        if (index > end) {
          spans.add(TextSpan(text: text.substring(end, index), style: style));
        }
        spans.add(TextSpan(
          text: link.text,
          style: link.style,
          recognizer: TapGestureRecognizer()..onTap = link.onTap,
        ));
        end = index + link.text.length;
      }
      if (i == length - 1 && end < text.length) {
        spans.add(TextSpan(text: text.substring(end), style: style));
      }
    }

    return RichText(
      text: TextSpan(children: spans, style: style),
    );
  }
}
